package com.pfzy.lib.net.convert;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.internal.$Gson$Types;
import com.pfzy.lib.net.BaseEntity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * 响应
 * @param <T>
 */
public class CCResponseConverter<T> implements Converter<ResponseBody, T> {
    public static boolean sJsonRepair = false;
    private final Gson gson;
    private CCConverterFactory.ResponseJsonParser mParser;
    private Type type;

    public CCResponseConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    public void setParser(CCConverterFactory.ResponseJsonParser parser) {
        this.mParser = parser;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String body = value.string();
        if(TextUtils.isEmpty(body)) {
            return null;
        }

        try {
            T parse = (T) this.mParser.parse(body, this.type);
            if (!sJsonRepair) {
                return (this.mParser == null || parse == null) ? (T) this.gson.fromJson(body, this.type) : parse;
            }
            return (this.mParser == null || parse == null) ? (T) this.gson.fromJson(body, this.type) : parse;
        }
        catch (Exception e) {
            e.printStackTrace();
            if ($Gson$Types.getRawType(this.type) == String.class) {
                return (T) body;
            }
            if ($Gson$Types.getRawType(this.type) != BaseEntity.class) {
                return null;
            }
            return repairBaseEntity(body);
        }
        finally {
            value.close();
        }
    }

    private T repairBaseEntity(String response) {
        BaseEntity retn = gson.fromJson(response, (Type) BaseEntity.class);
        retn.data = null;

        // 返回表示此类型的实际类型参数的Type对象数组。
        Type[] args = ((ParameterizedType) this.type).getActualTypeArguments();

        if ((args != null || args.length != 0) && $Gson$Types.getRawType(args[0]) == String.class) {
            try {
                JSONObject object = new JSONObject(response);
                retn.data = (T) object.get("data").toString();
            } catch (JSONException e) {
                retn.data = null;
            }
        }
        return (T) retn;
    }
}
